package kamikaze;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;

import javax.servlet.http.HttpSession;

import kamikaze.entity.Order;
import kamikaze.entity.OrderItem;
import kamikaze.entity.Product;
import kamikaze.support.ServiceContext;

public class ShoppingCart implements Serializable {

	public static class LineItem implements Serializable {
		private int amount = 1;
		private Product product;

		public LineItem(Product product) {
			this.product = product;
		}

		public Product getProduct() {
			return product;
		}

		public int getAmount() {
			return amount;
		}

		public BigDecimal getPrice() {
			return product.getPrice().multiply(BigDecimal.valueOf(amount));
		}
	}

	private Long userId;
	private HashMap<Long, LineItem> items = new HashMap<Long, LineItem>();

	public static ShoppingCart from(ServiceContext ctx) {

		HttpSession session = ctx.getRequest().getSession(true);
		ShoppingCart cart = (ShoppingCart) session.getAttribute("ShoppingCart");

		if (cart == null) {
			cart = new ShoppingCart();
			session.setAttribute("ShoppingCart", cart);
		}

		cart.userId = ctx.getUserSession().asUser().getId();
		return cart;

	}

	public Collection<LineItem> getItems() {
		return Collections.unmodifiableCollection(items.values());
	}

	public void add(Product prod) {

		Long key = prod.getKey().getId();

		if (!items.containsKey(key)) {
			items.put(key, new LineItem(prod));

		} else {
			items.get(key).amount++;
		}

	}

	public BigDecimal getTotalPrice() {
		BigDecimal totalPrice = BigDecimal.ZERO;

		for (LineItem item : items.values()) {
			totalPrice = totalPrice.add(item.getPrice());
		}

		return totalPrice;
	}

	public Order toOrder() {

		Order order = new Order();

		for (LineItem item : items.values()) {
			order.addItem(new OrderItem(item.getProduct().getName(), item.getProduct().getPrice(), item.getAmount(),
					item.getProduct().getProductId()));
		}

		order.setDescription("");
		order.setTotalPrice(getTotalPrice());
		order.setUserId(userId);

		items.clear();
		return order;
	}
}
